/**
 * 炮塔
 */
class TurretSprite extends egret.Sprite {
	// 子弹数组
	private _bulletSprites: Array<BulletSprite> = [];

	public constructor() {
		super();
		this.initTurret();
	}
	/**
	 * 初始化炮塔
	 */
	public initTurret(): void {
		// 炮塔背景
		var turretBitmapBg: egret.Bitmap = new egret.Bitmap(RES.getRes('turret_json.turret1Bg'));
		this.addChild(turretBitmapBg);
		this.setChildIndex(turretBitmapBg, 0);

		// 炮塔
		var turretBitmap: egret.Bitmap = new egret.Bitmap(RES.getRes('turret_json.turret1'));
		this.addChild(turretBitmap);
		this.setChildIndex(turretBitmap, 2);

		// 锚点设置
		this.anchorOffsetX = this.width / 2;
		this.anchorOffsetY = this.height / 2;
	}
	/**
	 * 填充子弹
	 */
	public fillBullet(bulletType: BulletType): void {
		var bulletSprite = new BulletSprite(bulletType);
		bulletSprite.startAnimation();
		bulletSprite.rotation = 180;
		bulletSprite.x = this.width / 2;
		bulletSprite.y = bulletSprite.height / 3;

		this.addChild(bulletSprite);
		this.setChildIndex(bulletSprite, 1);
		this._bulletSprites.push(bulletSprite);
		this.updateBullet();
	}

	/**
	 * 更新子弹在炮塔的位置
	 */
	public updateBullet() {
		for (var i: number = 0; i < this._bulletSprites.length; i++) {
			var tmpBulletSprite = this._bulletSprites[i];
			tmpBulletSprite.x = this.width / 2;
			if (i == 0) {
				tmpBulletSprite.y = tmpBulletSprite.height / 3;
			} else {
				tmpBulletSprite.y = this.height / 2;
			}
		}
	}

	/**
	 * 子弹发射
	 */
	public radiateBullet() {
		if (this._bulletSprites.length) {
			// 需要发射的子弹
			var bulletSprite = this._bulletSprites.shift();
			this.updateBullet();

			// 炮塔旋转角度（360°）
			var angle = this.rotation < 0 ? 360 + this.rotation : this.rotation;

			// 子弹口到炮塔的半径
			var r = this.height / 2 - bulletSprite.height / 3;
			// 炮塔的弧度
			var radian = angle * (Math.PI / 180);

			// 子弹在屏幕初始位置，采用三角函数运算
			var bulletX = this.x + r * Math.sin(radian);
			var bulletY = this.y - r * Math.cos(radian);

			// 位置设置
			bulletSprite.x = bulletX;
			bulletSprite.y = bulletY;
			bulletSprite.rotation = this.rotation > 0 ? this.rotation - 180 : this.rotation + 180;

			// 炮塔信息
			bulletSprite._turretPoint.x = this.x;
			bulletSprite._turretPoint.y = this.y;
			bulletSprite._turretDistance = r;
			bulletSprite._turretRadian = radian;

			// 移除炮塔上的子弹添加到屏幕上
			this.removeChild(bulletSprite);

			var gameContainer: GameContainer = this.parent as GameContainer;
			gameContainer._bulletSpriteRadiates.push(bulletSprite);
			gameContainer.addChild(bulletSprite);
		}
	}
}